/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.tsfile.core.service;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.api.service.MetadataProjectService;
import com.inspur.edp.lcm.metadata.api.service.MetadataService;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.tsfile.api.service.TsFileService;
import com.inspur.edp.web.tsfile.core.util.NameUtil;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import org.apache.commons.io.FilenameUtils;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * ts文件服务实现
 *
 * @author guozhiqi
 */
public class TsFileServiceImpl implements TsFileService {

    /**
     * 私有构造函数 避免外部私自实例化 提供统一返回实例方法
     */
    private TsFileServiceImpl() {

    }

    public static TsFileServiceImpl getNewInstance() {
        return new TsFileServiceImpl();
    }

    @Override
    public final void deleteTsFile(String fullPath) {
        FileUtility.deleteFile(fullPath);
    }

    @Override
    public final ArrayList<String> getTsFileList(String path) {
        throw new UnsupportedOperationException();
    }

    @Override
    public final boolean isTsFileExist(String fullPath) {
        throw new UnsupportedOperationException();
    }

    @Override
    public final String loadTsFileContent(String fullPath) {
        String filePath = getAbsolutePath(fullPath);
        return FileUtility.readAsString(filePath);
    }

    @Override
    public final String loadTsFileContentByWebCmp(String formRelativePath, String webCmpId) {
        String fileStr = "";
        MetadataProjectService metadataProjectService = SpringBeanUtils.getBean(MetadataProjectService.class);
        MetadataProject projInfo = metadataProjectService.getMetadataProjInfo(formRelativePath);
        MetadataService metadataService = SpringBeanUtils.getBean(MetadataService.class);
        List<GspMetadata> metadataList = metadataService.getMetadataList(projInfo.getProjectPath());

        GspMetadata webcmpMeta = null;
        for (GspMetadata item : metadataList) {
            if (webCmpId.equals(item.getHeader().getId())) {
                webcmpMeta = item;
                break;
            }
        }

        if (webcmpMeta == null) {
            throw new RuntimeException(String.format("没有找到表单对应的web构件。表单路径：｛%1$s｝，web构件id：｛%2$s｝", formRelativePath, webCmpId));
        }

        String fileName = webcmpMeta.getHeader().getFileName();
        String fullPath = webcmpMeta.getRelativePath() + "/" + fileName.substring(0, fileName.lastIndexOf(".")) + ".ts";
        return loadTsFileContent(fullPath);
    }

    @Override
    public String getTsClassNameByPath(String tsFilePath) {
        String fileName = FilenameUtils.getBaseName(tsFilePath);
        String normalized = NameUtil.getPascal(fileName);
        return normalized + "Service";
    }

    @Override
    public final void renameTsFile(String fullPath, String newName) {
        throw new UnsupportedOperationException();
    }

    @Override
    public final void saveTsFile(String fullPath, String content) {
        String absolutePath = getAbsolutePath(fullPath);
        FileUtility.writeFile(absolutePath, content);
    }

    /**
     * 获取绝对路径
     *
     * @param path
     * @return
     */
    private String getAbsolutePath(String path) {
        String unifiedPath = FileUtility.getPlatformIndependentPath(path);

        String devRootPath = FileUtility.getPlatformIndependentPath(MetadataUtility.getInstance().getDevRootPath());

        return unifiedPath.startsWith(devRootPath) ? unifiedPath : Paths.get(devRootPath).resolve((unifiedPath.startsWith("/") ? unifiedPath.substring(1) : unifiedPath)).toString();
    }

}
